from datetime import datetime

from flask import (Blueprint,
                   render_template,
                   request,
                   redirect,
                   url_for,
                   jsonify,
                   session,
                   flash)
from flask_mail import Message
from exts import mail
from exts import db
import string
import random
from .froms import (RegisterForm, LoginForm)
from models import (EmailCaptchaModel, UserModel)
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('user', __name__, url_prefix='/user')

captcha_base = string.ascii_letters + string.digits


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        login_form = LoginForm(request.form)
        if login_form.validate():
            email = login_form.email.data
            password = login_form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
            else:
                flash('邮箱和密码不匹配!')
                return redirect(url_for('user.login'))
        else:
            flash('邮箱或密码格式错误')
            return redirect(url_for('user.login'))


@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            # 密码加密
            user = UserModel(username=username, password=generate_password_hash(password), email=email)
            db.session.add(user)
            db.session.commit()

            return redirect(url_for('user.login'))
        else:
            return redirect(url_for('user.register'))


@bp.route('/captcha', methods=['POST'])
def get_captcha():
    email = request.form.get('email')
    if email:
        captcha = ''.join(random.sample(captcha_base, 4))
        message = Message(subject='知了问答', recipients=[email], body=f'你的注册验证码是\n{captcha}')
        mail.send(message)
        captcha_bean = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_bean:
            captcha_bean.captcha = captcha
            captcha_bean.create_time = datetime.now()
            db.session.commit()
        else:
            captcha_bean = EmailCaptchaModel(email=email, captcha=captcha)
            db.session.add(captcha_bean)
            db.session.commit()
        return jsonify({'code': 200})
    else:
        return jsonify({'code': 400, 'message': '请先传递邮箱'})


@bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('user.login'))
